<?php

namespace app\admin\controller;

use app\BaseController;
use app\common\exception\ParameterException;

class Base extends BaseController
{

    /**
     * @describe返回数据助手函数
     * @author: Bobo
     * @date: 2024-06-05 03:38:48
     * @param [int] $code [状态码]
     * @param [mixed] $data [数据] @required
     * @param [string] $msg [消息]
     * @return string 返回的JSON字符串
     */
    protected function returnJsonData(int $code, array|null $data = [], string $msg = '')
    {

        if (!is_numeric($code)) {
            throw new \think\Exception('The code must be a numeric value.');
        }

        $codeMessage = config()['code'];
        if (!isset($codeMessage[$code])) {
            throw new \think\Exception('The code does not have an associated message.');
        }

        $result = [
            'code' => $code,
            'message' => $msg ? $codeMessage[$code] . ',' . $msg : $codeMessage[$code],
            'data' => $this->escapeResult($data)
        ];


        return json($result);
    }

    /**
     * 清理参数数组
     *
     * @param array $params
     * @return array
     */
    protected function escapeResult($params)
    {
        if (is_array($params)) {
            foreach ($params as $key => &$value) {
                switch (strtoupper(gettype($value))) {
                    case 'ARRAY':
                        $value = $this->escapeResult($value);
                        break;
                    case 'STRING':
                        if (!is_null($value) && '' != $value) {
                            $value = htmlspecialchars_decode($value, ENT_QUOTES);
                        }
                        break;
                    default:
                        # code...
                        break;
                }

                // 这里可以根据需要添加更多的过滤条件

            }
        }
        return $params;
    }

    /**
     * 验证参数
     * @param array  $data     参数
     * @param string $validate 验证器
     */
    protected function validateData($data = [], $validate = '')
    {
        try {
            validate($validate)->check($data);
        } catch (\think\exception\ValidateException $e) {
            throw new ParameterException([
                'message' => $e->getError()
            ]);
        }
    }
}
